# -*- coding: utf-8 -*-
from PyQt5.QtGui import QTextCursor

__author__ = 'fg086897'

from time import ctime
from PyQt5 import QtWidgets
from DreamSerial_Ui import Ui_MainWindow as dreamSerial_MainWindow
import logging

logger = logging.getLogger('main.DreamSerial_UiHandler')


class DreamSerial_UiHandler(dreamSerial_MainWindow):
    def __init__(self, parent=None):
        dreamSerial_MainWindow.__init__(self)

    def getPortSettings(self):
        """
        This method will read out all serial setting in UI
        :return: settings of the serial.
        """
        settings = {"port": self.cbbPortName.currentText(), "baud": self.cbbBaudRate.currentText(),
                    "bytesize": int(self.cbbDataBit.currentText()), "parity": self.cbbParity.currentText()[:1],
                    "stopbits": int(self.cbbStopBit.currentText()), "timeout": 1}

        # For pySerial, parity input shoud be
        # PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
        logger.info(settings)
        return settings

    def getDataAndType(self):
        return self.leTx.text(), self.cbbTxType.currentText().lower()

    def onSendData(self, data=None, _type="ascii"):
        """
        This is the action when user pressed Send Button,
        :param data:
        :param _type:
        :return: data
        """
        _type = self.cbbTxType.currentText().lower();

        if not data:
            data = self.leTx.text()
        if _type == "hex":
            data = [int(x, 16) for x in data.replace('0x', '').split()]
        else:
            data = bytes(data, 'utf-8')

        if self.cbNewLine.isChecked():
            data += bytes('\r', 'utf-8')

#        self.leTx.clear()
        return data

    def onRecvData(self, data):
        # bytes = len(data)
        byteStr = str(data, encoding='utf-8')
        print(byteStr)
        self.pteRx.moveCursor(QTextCursor.End)
        self.pteRx.insertPlainText(byteStr)
